Page({
  data: {
    bookId: '',
    name: '',
    author: '',
    isbn: '',
    cloud: null
  },

  onLoad(options) {
    this.initSharedCloud();
    if (options.id) {
      this.setData({ bookId: options.id });
      this.loadBook();
    }
  },

  async initSharedCloud() {
    const cloud = new wx.cloud.Cloud({
      resourceAppid: 'wx3199c80279c7b8c3',
      resourceEnv: 'education-6gwexwp8488514df'
    });
    
    try {
      await cloud.init();
      this.setData({ cloud });
    } catch (err) {
      console.error('初始化云环境失败：', err);
    }
  },

  async loadBook() {
    try {
      const { cloud, bookId } = this.data;
      const db = cloud.database();
      const { data } = await db.collection('books').doc(bookId).get();
      
      this.setData({
        name: data.name,
        author: data.author,
        isbn: data.isbn
      });
    } catch (err) {
      console.error('加载书籍失败：', err);
    }
  },

  onNameInput(e) {
    this.setData({
      name: e.detail.value
    });
  },

  onAuthorInput(e) {
    this.setData({
      author: e.detail.value
    });
  },

  onIsbnInput(e) {
    this.setData({
      isbn: e.detail.value
    });
  },

  async handleSave() {
    const { name, author, isbn, bookId, cloud } = this.data;
    
    if (!name || !author || !isbn) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'none'
      });
      return;
    }

    try {
      const db = cloud.database();
      const bookData = {
        name,
        author,
        isbn,
        updateTime: db.serverDate()
      };

      if (bookId) {
        // 更新书籍
        await db.collection('books').doc(bookId).update({
          data: bookData
        });
      } else {
        // 新增书籍
        bookData.createTime = db.serverDate();
        await db.collection('books').add({
          data: bookData
        });
      }

      wx.showToast({
        title: '保存成功',
        icon: 'success'
      });

      setTimeout(() => {
        wx.navigateBack();
      }, 1500);

    } catch (err) {
      console.error('保存书籍失败：', err);
      wx.showToast({
        title: '保存失败，请重试',
        icon: 'error'
      });
    }
  }
}); 